package com.kinglumi.ailighting.auth.util;

import java.util.Random;

public class DesUtil {
    private static String ALGORITHM = "ABCDEFGHIJKLMNPQRSTUVWXYZ";


    /**
     * 加密
     *
     * @param n id0四位随机数
     * @return 邀请码
     */
    public static String base34(int n) {
        int[] array = new int[6];
        int i = 0;

//        while (n > 0) {
//            int a = n % 34;
//            array[i++] = a;
//            n = n / 34;
//        }

        while (n > 0) {
            int a = n % 25;
            array[i++] = a;
            n = n / 25;
        }

        StringBuilder result = new StringBuilder();
        for (int j = array.length - 1; j >= 0; j--) {
            result.append(ALGORITHM.charAt(array[j]));
        }
        return result.toString();
    }

    public static int getIndex(char a) {
        char[] chars = ALGORITHM.toCharArray();
        for (int i = 0; i < ALGORITHM.length(); i++) {
            if (a == chars[i]) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 解析 邀请码
     *
     * @param code 邀请码
     */
    public static int base10(String code) {

        char[] chars = code.toCharArray();
        int[] arr = new int[6];
        for (int i = 0; i < 6; i++) {
            arr[i] = getIndex(chars[i]);
        }
        int num = 0;
//        num = arr[5] + arr[4] * 34 + arr[3] * 34 * 34 + arr[2] * 34 * 34 * 34 +
//                arr[1] * 34 * 34 * 34 * 34 + arr[0] * 34 * 34 * 34 * 34 * 34;

        num = arr[5] + arr[4] * 25 + arr[3] * 25 * 25 + arr[2] * 25 * 25 * 25 +
                arr[1] * 25 * 25 * 25 * 25 + arr[0] * 25 * 25 * 25 * 25 * 25;


        return num;
    }

    /**
     * 解密后 解析出meshId
     *
     * @param code 邀请码
     */
    public static String getMeshId(String code) {
        int pos = code.lastIndexOf("0");
        return code.substring(0, pos);
    }


    public static void main(String[] args) {
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            code.append(new Random().nextInt(9) + 1);
        }
        StringBuilder buffer = new StringBuilder();
        StringBuilder invitationCode = buffer.append("421").append(0).append(code);
        String s = invitationCode.toString();
        // 加密
        String base34 = DesUtil.base34(Integer.valueOf(s));

        System.out.println(base34);

        int i = DesUtil.base10(base34);
       String  meshId = DesUtil.getMeshId(String.valueOf(i));

        System.out.println(meshId);
    }

}
